package org.jash.attendance.ui

import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.ObservableField
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.utils.DistanceUtil
import kotlinx.coroutines.launch
import org.jash.attendance.R
import org.jash.attendance.BR
import org.jash.attendance.databinding.ActivitySignBinding
import org.jash.attendance.entity.SignEntity
import org.jash.attendance.model.SignIntent
import org.jash.attendance.model.SignState
import org.jash.attendance.model.SignViewModel
import org.jash.common.adapter.CommonAdapter
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseActivity
import org.jash.common.mvi.BaseState
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.log

@Route(path = "/attendance/sign")
class SignActivity : BaseActivity<ActivitySignBinding, SignViewModel>() {
    val adapter by lazy { CommonAdapter<SignEntity>({R.layout.item_sign to BR.sign}) }
    var signInfo:Map<String, Any>? = null
    val locationClient by lazy { LocationClient(this, LocationClientOption().apply {
        coorType = BDLocation.BDLOCATION_GCJ02_TO_BD09LL
        setIsNeedAddress(true)
        openGps = true
    })}
    val locationListener: BDAbstractLocationListener by lazy {
        object :BDAbstractLocationListener() {
            override fun onReceiveLocation(location: BDLocation?) {
                logDebug("onReceiveLocation: ${location}")
                location?.let {
                    val distance = DistanceUtil.getDistance(
                        LatLng(39.170952, 116.94557),
                        LatLng(it.latitude, it.longitude)
                    )
                    logDebug("直线距离: $distance")

                    if (distance < 10000000) {
                        signInfo = mapOf(
                            "userId" to 1,
                            "SignLat" to it.latitude,
                            "SignLong" to it.longitude
                        )
                    }
                }
            }
        }
    }
    val sdf by lazy { SimpleDateFormat("EEE", Locale.SIMPLIFIED_CHINESE) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.recycler.adapter = adapter
        binding.week.text = "时间${sdf.format(Date())}"
        lifecycleScope.launch {
            viewModel.intent.send(SignIntent.SelSign(1, 1))
        }
        SDKInitializer.setAgreePrivacy(applicationContext, true)
        SDKInitializer.initialize(applicationContext)
        SDKInitializer.setCoordType(CoordType.BD09LL)
        LocationClient.setAgreePrivacy(true)
        locationClient.registerLocationListener(locationListener)
        locationClient.start()
        binding.sign.setOnClickListener {
            if (signInfo != null) {
                lifecycleScope.launch {
                    viewModel.intent.send(SignIntent.Sign(signInfo!!))
                }
            } else {
                Toast.makeText(this, "未到公司不能打卡", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        locationClient.stop()
    }
    fun loadedSign(list:SignState.SignList) {
        adapter += list.signList
    }
    fun error(error:BaseState.Error) {
        Toast.makeText(this, error.msg, Toast.LENGTH_SHORT).show()
        logDebug(error.msg)
    }

    fun response(res:SignState.SignResponse) {
        Toast.makeText(this, "打卡${if(res.flag) "成功" else "失败"}", Toast.LENGTH_SHORT).show()
    }

}